<template>
  <div :ref="getButtonRef" @click.stop v-click-outside="onClickOutside">
    <svg-icon :icon-class="tableHeaderItem.isSetFilter ? 'filter-icon-active' : 'filter-icon'" link />
  </div>
  <el-popover
    ref="popoverRef"
    :virtual-ref="buttonRef"
    :placement="tableHeaderItem.value === 'customerName' ? 'right' : 'bottom'"
    trigger="click"
    virtual-triggering
    :show-arrow="false"
    popper-class="custom-popover"
    @show="handelOpenFilter"
    @hide="handelHideFilter"
  >
    <component
      v-if="isOpenPopover"
      :is="headerCmps[tableHeaderItem.value]"
      :cmps-title="tableHeaderItem.label"
      :filter-list="filterData"
      @handel-filter-data="handelFilterData"
    />
  </el-popover>
</template>

<script setup>
import { ref, unref, nextTick, watch } from "vue";
import { ClickOutside as vClickOutside } from "element-plus";
import { cloneDeep } from "lodash";
import { headerCmps } from "@/views/engineeringManage/config/baseConfig";

const props = defineProps({
  tableHeaderItem: {
    type: Object,
    default: () => ({})
  },
  columnIndex: {
    type: Number,
    default: 0
  }
});
const emit = defineEmits(["handelFilterData"]);
const filterData = ref([]);

watch(
  () => props.tableHeaderItem,
  newVal => {
    filterData.value = cloneDeep(newVal.filterList ?? []);
  },
  { immediate: true, deep: true }
);

const isClickOutside = ref(false);
const isOpenPopover = ref(false);

/**
 * 打开筛选弹窗，初始化数据
 */
const handelOpenFilter = async () => {
  await nextTick();
  isOpenPopover.value = true;
  unref(popoverRef).popperRef?.popperInstanceRef?.update();
};
/**
 * 点击外部，关闭筛选弹窗，恢复之前数据
 */
const handelHideFilter = () => {
  if (isClickOutside.value) {
    filterData.value = cloneDeep(props.tableHeaderItem.filterList);
  }
  isOpenPopover.value = false;
};

const buttonRef = ref(null);
const popoverRef = ref(null);
const getButtonRef = e => {
  buttonRef.value = e;
};
const onClickOutside = async () => {
  await nextTick();
  isClickOutside.value = true;
  unref(popoverRef).popperRef?.delayHide?.();
};

/**
 * 确定回传数据
 * @param filterData
 */
const handelFilterData = filterData => {
  isClickOutside.value = false;
  popoverRef.value.hide();
  emit("handelFilterData", { filterData, columnIndex: props.columnIndex, isRefresh: true });
};
</script>

<style lang="scss">
.custom-popover {
  width: fit-content !important;
  padding: 0 !important;
}
</style>

<style scoped lang="scss">
@use "@/assets/styles/mixin";

.svg-icon {
  cursor: pointer;
}

.filter-table-header {
  .condition {
    padding: 12px;
    box-sizing: border-box;
    border-bottom: 1px solid #d7d8e0;
  }
  .filter-buttons {
    @include mixin.flex-center;
    padding: 12px;
    box-sizing: border-box;
    :deep(.el-button) {
      width: 130px;
      height: 28px;
    }
  }
}
.filter-icon-active {
  padding: 3px;
  border-radius: 2px;
  background-color: #e7eaf0;
}
</style>
